package org.elfen.redis.service;

import org.elfen.common.Constants;
import org.elfen.common.Token;
import org.elfen.common.util.DataUtil;
import org.elfen.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;


@Service
public class RedisServiceImpl implements RedisService{
	@Autowired
	private RedisUtil redisUtil;
	
	@Override
	public boolean saveToken2Redis(Token token) {
		String key = Constants.TOKEN_KEY+":"+token.getTokenKey();
		String value = JSON.toJSONString(token);
		Long expireTime = Long.parseLong(Constants.TOKEN_EXPIRATION);
		
		return redisUtil.set(key, value, expireTime);
	}

	@Override
	public void deleteToken2Redis(String tokenKey) {
		String key = Constants.TOKEN_KEY+":"+tokenKey;
		redisUtil.remove(key);
	}

	@Override
	public Token selectToken2Redis(String tokenKey) {
		String key = Constants.TOKEN_KEY+":"+tokenKey;
		String value = (String) redisUtil.get(key);
		if(DataUtil.isNotEmpty(value)){
			Token tokenInfo = JSON.parseObject(value, Token.class);
			return tokenInfo;
		}else{
			return null;
		}
	}

	@Override
	public boolean saveData2Redis(String key, Object entity) {
		String value = JSON.toJSONString(entity);
		return redisUtil.set(key, value);
	}

	@Override
	public String selectData2Redis(String key) {
		return (String) redisUtil.get(key);
	}

	@Override
	public String subscribe(String topic) {
		return redisUtil.subscribe(topic);
	}

	@Override
	public void sendMessage2Topic(String topic, String jsonString) {
		System.out.println("jsonString="+jsonString);
		redisUtil.publish(topic, jsonString);
	}

}
